#!/usr/bin/env python

import thread
import time
import urllib2

import battlefield_ui
import battlefield_data

cli = battlefield_ui.cli("rulai")
data = battlefield_data.data("http://wss-9:8000", "http://wss-9:8001")


def do_get_player(player_name):
    try:
        return data.get_player(player_name)
    except urllib2.HTTPError, e:
        if 404 == e.code:
            cli.print_error("player cannot be found")
        elif 500 == e.code:
            cli.print_error("internal error")
        return False

def do_get_action(player_name):
    try:
        return data.get_action(player_name)
    except urllib2.HTTPError, e:
        if 404 == e.code:
            return None
        elif 500 == e.code:
            cli.print_error("internal error")
            return False
        
def loop(sleep_time, lock):
    cli.print_info("start looping...")
    while (True):
        govern()
        time.sleep(sleep_time)
    lock.release()

def govern():
        try:
            player_map = data.get_player_map()
            for player_name, location in player_map.items():
                apply_action(player_name, location)
        except urllib2.HTTPError, e:
            if 404 == e.code:
                cli.print_error("player_list cannot be found")
            elif 500 == e.code:
                cli.print_error("internal error")

def apply_action(player_name):
    action = do_get_action(player_name)
    if None == action: return True
    
                
if __name__ == '__main__':
    cli.print_info("init")
    lock = thread.allocate_lock()
    lock.acquire()
    thread.start_new_thread(loop, (2, lock))
    while (lock.locked()): pass
    cli.print_info("exit")
    

